<template>
  <div>
    <el-form ref="pwdRef" :model="user" :rules="rules" label-width="80px">
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input
          v-model="user.oldPassword"
          placeholder="请输入旧密码"
          type="password"
          show-password
        />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          v-model="user.newPassword"
          placeholder="请输入新密码"
          type="password"
          show-password
        />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="user.confirmPassword"
          placeholder="请确认新密码"
          type="password"
          show-password
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit(pwdRef)">保存</el-button>
        <el-button @click="resetFrom()">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, defineExpose } from 'vue'
import {
  checkOldPassword,
  submitNewPassword
} from '@/api/indivdual/resetPassword.js'

import { ElMessage } from 'element-plus'

import { useStore } from 'vuex'
const store = useStore()
const userId = store.state.app.user.id
const pwdRef = ref()
const user = ref({
  oldPassword: undefined,
  newPassword: undefined,
  confirmPassword: undefined
})

const equalToPassword = (rule, value, callback) => {
  if (user.value.newPassword !== value) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const rules = ref({
  oldPassword: [{ required: true, message: '旧密码不能为空', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '新密码不能为空', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value === user.value.oldPassword) {
          callback(new Error('新密码不能和旧密码相同'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    },
    {
      pattern: /^(?=.*[0-9])(?=.*[a-zA-Z])[0-9a-zA-Z]{8,16}$/,
      message: '密码必须是8-16位的数字和字母组合',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '确认密码不能为空', trigger: 'blur' },
    { required: true, validator: equalToPassword, trigger: 'blur' }
  ]
})

/** 提交按钮 */
const submit = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await checkOldPassword({
        user_id: userId,
        origPwd: user.value.oldPassword
      })
        .then(async (res) => {
          if (!res.data) {
            ElMessage.error('旧密码错误')
          } else {
            await submitNewPassword({
              user_id: userId,
              newPwd: user.value.confirmPassword
            })
              .then((res) => {
                ElMessage.success('密码修改成功，请重新登录')
                resetFrom()
                setTimeout(() => {
                  store.dispatch('app/logout')
                }, 2000)
              })
              .catch((err) => {
                console.log(err)
              })
          }
        })
        .catch((err) => {
          console.log(err)
        })
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 重置
const resetFrom = () => {
  pwdRef.value.resetFields()
}
defineExpose({ resetFrom })
</script>
